package cn.xd.base.domain.entity;

import cn.hutool.core.util.StrUtil;
import cn.xd.base.basic.type.*;
import cn.xd.base.domain.bean.command.CreateUserCommand;
import cn.xd.common.enums.common.CommonStatusEnum;
import cn.xd.core.basic.common.CreateTime;
import cn.xd.core.ddd.EntityObject;
import cn.xd.core.ddd.entity.Aggregate;
import lombok.Builder;
import lombok.Data;

import java.util.List;

@Builder
@Data
public class GlobalAppUser implements Aggregate<GlobalAppUserId> {

    private GlobalAppUserId id;

    /**
     * 昵称
     */
    private NickName nickName;

    /**
     * 性别
     */
    private Gender gender;

    /**
     * 头像
     */
    private AvatarUrl avatarUrl;

    /**
     * 状态字典common_status，用于冻结用户
     */
    private CommonStatus status;

    /**
     * 电话号码
     */
    private Phone phone;

    private Password password;

    /**
     * 创建时间
     */
    private CreateTime createTime;

    private FromWay fromWay;

    private FromId fromId;

    private AppUserType fromApp;

    /**
     * 与第三方应用关联
     */
    @EntityObject
    private List<AppUserThirdParty> thirdPartyList;

    public static GlobalAppUser register(CreateUserCommand command) {
        GlobalAppUser newUser = GlobalAppUser.builder()
                .nickName(NickName.of(command.getNickName()))
                .gender(Gender.of(command.getGender()))
                .avatarUrl(AvatarUrl.of(command.getAvatarUrl()))
                .status(CommonStatus.of(CommonStatusEnum.ENABLE.getCode()))
                .phone(Phone.of(command.getPhone()))
                .fromWay(FromWay.of(command.getFromWay()))
                .fromId(FromId.of(command.getFromId()))
                .fromApp(AppUserType.of(command.getFromApp()))
                .createTime(CreateTime.now())
                .password(Password.of(null))
                .thirdPartyList(AppUserThirdParty.add(command.getThirdPartyCmd()))
                .build();
        if (StrUtil.isNotBlank(command.getPassword())) {
            newUser.changePassword(Password.encrypt(command.getPassword()));
        }
        return newUser;
    }

    /**
     * 新增第三方信息
     *
     * @param openId
     * @param unionId
     * @param type
     * @param appUserType
     */
    public void addThirdPartyList(String openId, String unionId, Integer type, Integer appUserType) {
        getThirdPartyList().add(AppUserThirdParty.add(getId(), openId, unionId, type, appUserType));
    }

    public void changePassword(Password password) {
        this.password = password;
    }


    public void markAsDelete() {
        this.status = CommonStatus.of(CommonStatusEnum.DELETED.getCode());
    }

}

